namespace mecs {

    export class CompCreater {

        private _pool: { [compName: string]: BaseComp[] };

        private _compClsHash: { [compName: string]: any };
        constructor() {
        }

        regClsHash(compName: string, compCls: any) {
            if (!this._compClsHash) {
                this._compClsHash = {}
            }
            if (!this._compClsHash[compName]) {
                this._compClsHash[compName] = compCls;
            }
        }

        getComp(compCls: any, data?: any) {
            let name = compCls.NAME;
            this._init(name);
            let list = this._pool[name];
            if (list.length) {
                let comp = this._pool[name].pop();
                comp.resetData(data);
                return comp;
            } else {
                return this.createComp(compCls, data);
            }
        }

        cache(comp: BaseComp) {
            if (!comp) return;

            this._init(comp.compName);
            comp.clear();
            this._pool[comp.compName].push(comp);
        }

        createComp(cls: any, data?: any) {
            this.regClsHash(cls.NAME, cls);
            let c = new cls(data);
            return c;
        }

        createCompByCache(compName: string, data?: any) {
            let cls = this._compClsHash[compName];
            if (!cls) {
                return null;
            }
            let c: BaseComp = new cls();
            c.resetData(data);
            return c;
        }

        private _init(name: string) {
            if (!this._pool) {
                this._pool = {}
            }
            if (!this._pool[name]) {
                this._pool[name] = [];
            }
        }

        dispose() {
            this._pool = null;
            this._compClsHash = null;
        }
    }
}